#!/usr/bin/env python3
"""
修复OpenMemory中重复应用的问题
这个脚本会查找并合并同名的重复应用
"""

import uuid
from sqlalchemy.orm import Session
from app.database import SessionLocal
from app.models import App, Memory, MemoryAccessLog


def find_duplicate_apps(user_id: str, target_name: str = "OpenMemory"):
    """查找指定用户的重复应用"""
    db = SessionLocal()
    try:
        # 获取用户
        from app.models import User
        user = db.query(User).filter(User.user_id == user_id).first()
        if not user:
            print(f"用户 {user_id} 不存在")
            return []
        
        # 查找所有匹配的应用
        apps = db.query(App).filter(
            App.owner_id == user.id,
            App.name.ilike(f"%{target_name}%")
        ).all()
        
        return apps
    finally:
        db.close()


def merge_duplicate_apps(keep_app_id: str, merge_app_ids: list):
    """合并重复应用的记忆到保留的应用"""
    db = SessionLocal()
    try:
        keep_app = db.query(App).filter(App.id == uuid.UUID(keep_app_id)).first()
        if not keep_app:
            print(f"保留的应用 {keep_app_id} 不存在")
            return False
        
        merged_count = 0
        for merge_app_id in merge_app_ids:
            merge_app = db.query(App).filter(App.id == uuid.UUID(merge_app_id)).first()
            if not merge_app:
                continue
            
            # 更新Memory表
            memories = db.query(Memory).filter(Memory.app_id == uuid.UUID(merge_app_id)).all()
            for memory in memories:
                memory.app_id = keep_app.id
                merged_count += 1
            
            # 更新MemoryAccessLog表
            logs = db.query(MemoryAccessLog).filter(MemoryAccessLog.app_id == uuid.UUID(merge_app_id)).all()
            for log in logs:
                log.app_id = keep_app.id
            
            # 删除合并的应用
            db.delete(merge_app)
            print(f"已合并应用 {merge_app.name} ({merge_app_id}) 的 {len(memories)} 条记忆")
        
        db.commit()
        print(f"总共合并了 {merged_count} 条记忆到应用 {keep_app.name}")
        return True
        
    except Exception as e:
        db.rollback()
        print(f"合并过程中出错: {e}")
        return False
    finally:
        db.close()


def list_all_apps_for_user(user_id: str):
    """列出用户的所有应用"""
    db = SessionLocal()
    try:
        from app.models import User
        user = db.query(User).filter(User.user_id == user_id).first()
        if not user:
            print(f"用户 {user_id} 不存在")
            return
        
        apps = db.query(App).filter(App.owner_id == user.id).order_by(App.name).all()
        
        print(f"\n用户 {user_id} 的所有应用:")
        print("-" * 80)
        for app in apps:
            memory_count = db.query(Memory).filter(Memory.app_id == app.id).count()
            print(f"ID: {app.id} | 名称: '{app.name}' | 记忆数: {memory_count} | 状态: {'活跃' if app.is_active else '暂停'}")
        
    finally:
        db.close()


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) < 2:
        print("用法: python fix_duplicate_apps.py <user_id> [app_name]")
        sys.exit(1)
    
    user_id = sys.argv[1]
    app_name = sys.argv[2] if len(sys.argv) > 2 else "OpenMemory"
    
    print(f"查找用户 {user_id} 的重复应用 '{app_name}'...")
    
    # 列出所有应用
    list_all_apps_for_user(user_id)
    
    # 查找重复应用
    duplicate_apps = find_duplicate_apps(user_id, app_name)
    
    if len(duplicate_apps) <= 1:
        print(f"没有找到重复的 '{app_name}' 应用")
    else:
        print(f"\n找到 {len(duplicate_apps)} 个 '{app_name}' 应用:")
        for i, app in enumerate(duplicate_apps):
            memory_count = len(app.memories)
            print(f"{i+1}. ID: {app.id} | 记忆数: {memory_count}")
        
        # 建议保留第一个创建的应用
        keep_app = duplicate_apps[0]
        merge_apps = [app.id for app in duplicate_apps[1:]]
        
        print(f"\n建议保留: {keep_app.id} (最早创建)")
        print(f"将合并以下应用: {[str(app.id) for app in duplicate_apps[1:]]}")
        
        confirm = input("确认合并? (y/N): ")
        if confirm.lower() == 'y':
            merge_duplicate_apps(str(keep_app.id), [str(app_id) for app_id in merge_apps])
            print("合并完成!")
        else:
            print("取消合并")